package com.lancoo.answer.manager;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;



import java.lang.ref.WeakReference;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MediaManager {

    private static final String TAG = "MediaManager";
    private MediaPlayer mMediaPlayer;
    private boolean isPause,isPrepared,isStoped;
    private WeakReference<OnPlayListener> mListener;
    private Context mContext;
    private ExecutorService mSingleExecutor;
    private boolean isStop;
    private volatile boolean mIsSeekComplete = true;
    private String path;

    //旧方法，不再使用
    public MediaManager(Context mContext){
        this.mContext=mContext.getApplicationContext();
        mSingleExecutor = Executors.newSingleThreadExecutor();
    }

    public void setUpMedia(String filePath, final OnPlayListener listener) {
        path=filePath;
        isPause=false;
        isStoped=false;
        mListener = new WeakReference<>(listener);
        if(TextUtils.isEmpty(filePath)){
            mListener.get().onSourceError();
            return;
        }
        if(filePath.length()>8){
            String reg="[/]+";
            String port=filePath.substring(0,8);
            String content=filePath.substring(8);
            Matcher matcher= Pattern.compile(reg).matcher(content);
            while (matcher.find()){
                content=content.replace(matcher.group(),"/");
            }
            filePath=port+content;
        }
        Log.e("aaaa","music 转换后的url:"+filePath);
        if (null == mMediaPlayer) {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.reset();
            mMediaPlayer.setOnBufferingUpdateListener((mediaPlayer, percent) -> {
                Log.e(TAG, percent+"-> onBuffer: "+path );
                if (listener != null) {
                    listener.onBufferingUpdate(mMediaPlayer, percent);
                }
            });
            mMediaPlayer.setOnErrorListener((mediaPlayer, i, i1) -> {
                Log.e(TAG, i+","+i1+" onError: "+path );
                mMediaPlayer.reset();
                if (listener != null&&!isStoped) {
                    listener.onStartError();
                }
                return true;
            });
        } else {
            mMediaPlayer.reset();

        }
        isPrepared=false;
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setOnCompletionListener(mediaPlayer -> {
            Log.e(TAG, "onComplete: "+path );
            if (null != listener) {
                seekTo(0);
                listener.onComplete();
            }
        });
        try {
//            Uri uri=Uri.parse(filePath);
            mMediaPlayer.setDataSource(filePath);
            mMediaPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
            if (listener != null) {
                listener.onSourceError();
            }
        }
        mMediaPlayer.setOnPreparedListener(mediaPlayer -> {
            isPrepared=true;
            Log.e(TAG, "onPrepare: "+path );
            if (listener != null&&!isPause) {
                listener.onPrepare();
            }
        });
        mMediaPlayer.setOnSeekCompleteListener(mp -> mIsSeekComplete = true);

    }


    public void start() {
        Log.e(TAG,"start");
        if (null != mMediaPlayer&&isPrepared) {
            isPause=false;
            try{
                mMediaPlayer.start();
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        if(mContext==null){
            return;
        }
        if(isStop){
            return;
        }
        isStop=true;

        AudioManager audioManager= (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        audioManager.requestAudioFocus(focusChange -> {
            if(focusChange==-1){
                isStop=false;
                if(mContext!=null&&mContext.getMainLooper()!=null){
                    new Handler(mContext.getMainLooper()).post(this::pause);
                }

            }
            Log.e("aaaaaaaaa","onAudioFocusChange,onAudioFocusChange,onAudioFocusChange:"+
                    focusChange);
        }, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
        Log.e("aaaa","AudioManager,AudioManager,AudioManager,AudioManager,AudioManager22");
    }

    public void pause() {
        if(isPause){
            return;
        }
        isPause = true;
        if (null != mMediaPlayer && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            if (null != mListener) {
                mListener.get().onPausePlay();
            }
        }
    }

    public void release() {
        if (mSingleExecutor!=null
                && !mSingleExecutor.isShutdown()){
            mSingleExecutor.shutdownNow();
            mSingleExecutor = null;
        }
        if (null != mMediaPlayer) {
            isPause = false;
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }


    public void seekTo(final int msec) {
        if(mSingleExecutor==null){
            return;
        }
        mSingleExecutor.execute(() -> {
            if (mMediaPlayer != null&&isPrepared) {
                mIsSeekComplete = false;
                mMediaPlayer.seekTo(msec);
            }
        });
    }

    public boolean isPause() {
        return isPause;
    }
    public boolean isPrepared() {
        return isPrepared;
    }


    public boolean isPlay() {
        if (mMediaPlayer != null) {
            try{
                return mMediaPlayer.isPlaying();
            }catch (Exception e){
               e.printStackTrace();
            }
        }
        return false;
    }

    public int getDuring() {
        Log.e(TAG,"getDuring");
        if (mMediaPlayer != null && isPrepared) {
            return (int)mMediaPlayer.getDuration();
        }

        return 0;
    }

    public int getCurrentPosition() {
        if (mMediaPlayer != null && isPrepared) {
            return (int)mMediaPlayer.getCurrentPosition();
        }
        return 0;
    }


    public interface OnPlayListener {
        void onComplete();

        void onStartError();

        void onPausePlay();

        void onSourceError();

        void onStopPlay();

        void onPrepare();

        void onBufferingUpdate(MediaPlayer mp, int percent);

    }

    public void stop() {
        if (null != mMediaPlayer) {
            mMediaPlayer.stop();
            isPause = false;
            Log.e("music","音频重置了");
            isPrepared=false;
        }
    }

    public void setPlaySpeed(final float speed){
        if(Build.VERSION.SDK_INT> Build.VERSION_CODES.N&&isPrepared){
            try{
                mSingleExecutor.execute(() -> {
                    try{
                        if (mIsSeekComplete)
                            mMediaPlayer.setPlaybackParams(mMediaPlayer.getPlaybackParams().setSpeed(speed));
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                });
            }catch (Exception e){
                Log.e("aaaa","IllegalStateException:"+ e);
            }

        }
    }

}
